global state_name = "Pennsylvania"

//set working directory 
cd  "C:\Users\johna\Dropbox (Curiel Analytx)\ElectionNightResults\replication_code"
//the above is just the path to the replcation files. The data from here on are 
//hierarchical and nested from this file path. 


import delimited using "data\nyt_counties.csv", clear varn(1)
keep if state == "$state_name"
gen hoursfromclosing = clock(time,"YMD hms") - clock("2020-11-04 03:00:00","YMD hms")
drop if hours < 0
replace hours = hours/(60*60*1000)
sort name hoursfrom
gen finalvotes = votes if name ~= name[_n+1]
egen maxfinalvotes = max(finalvotes),by(name)
gen pctreported = 100*votes/maxfinalvotes
gen bidenpct = 100*bidenj/(bidenj + trumpd)
gen dbidenpct = 100*(bidenj - bidenj[_n-1])/(bidenj + trumpd - bidenj[_n-1] - trumpd[_n-1])
gen newvotes = bidenj + trumpd - bidenj[_n-1] - trumpd[_n-1] if name == name[_n-1]
drop if votes == votes[_n-1] & absentee_votes == absentee_votes[_n-1]
replace newvote = votes if name ~= name[_n-1]
sort name time votes
drop if votes == votes[_n-1] & absentee_votes == absentee_votes[_n-1]
gen inperson = votes - absentee_votes
drop if pctreported > 100
replace dbidenpct = 100*bidenj/(bidenj + trumpd) if name ~= name[_n-1]


** append a dummy observation at the 101% mark, to aid in graphing
preserve
keep if name ~= name[_n-1]
keep name 
gen pctreported = 101
save "data\scratch\pacounties", replace
restore
drop if pctreported > 100
append using "data\scratch\pacounties"
sort name pctreported
gen lastbiden = bidenj if pctreported[_n+1] == 101
gen lasttrump = trumpd if pctreported[_n+1] == 101
gen biden_win = lastbiden > lasttrump
egen max_biden_win = max(biden_win),by(name)

gen lastvotes = votes if pctreported[_n+1] == 101
egen max_lastvotes = max(lastvotes), by(name)

twoway (connected bidenpct pctreported if max_biden_win == 1 [aw=votes] ,cmissing(n) lwidth(vthin) lpattern(solid) lcolor(midblue) msymbol(circle) msize(tiny) mcolor(midblue%60)) ///
       (connected bidenpct pctreported if max_biden_win == 0 [aw=votes] ,cmissing(n) lwidth(vthin) lpattern(solid) lcolor(red) msymbol(circle) msize(tiny) mcolor(red%60)), ///
	   ytitle(Percent Biden two-party vote share) ///
	   xtitle(Percent reported) ///
	   legend(order(1 "Counties won by Biden" 2 "Counties won by Trump"))
graph export "figures\fig17c.png", replace width(2500)

areg bidenpct pctreported if max_biden_win == 1 [aw=votes], a(name) robust
areg bidenpct pctreported if max_biden_win == 0 [aw=votes], a(name) robust
